package cn.com.klun.tjy.other.ThreadsTest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class LinkedBlockingQueueTest {
    public static void main(String[] args) {
        LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
        ExecutorService service = Executors.newFixedThreadPool(5);
        service.execute(new Producer(queue));
        service.execute(new Consumer(queue));
    }
}
class Producer extends Thread{
    private LinkedBlockingQueue<String> queue;
    public Producer(LinkedBlockingQueue<String> queue){
        this.queue = queue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("生产出："+i);
            try {
                Thread.sleep(1000);
                queue.put(new String("producer:"+i));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Consumer extends Thread{
    private LinkedBlockingQueue<?> queue;
    public Consumer(LinkedBlockingQueue<String> q){
        this.queue = q;
    }
    @Override
    public void run() {
        while (true){
            try {
                System.out.println("consumer 消费了："+queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}





